

from flask import request
from utils.randomUtils import  generate_random_by_time
import threading
from .baseGraphNode import  *
from ..execute.baseExeHis import BaseExeHis
from .sessionInfo import SessionInfo
import time
class ProjectProcessGraphNode(BaseGraphNode):
    
    socketio_instances = {}
    def __init__(self, id:str, data:dict, graphNodeManager, random_key:str):
        super().__init__(id, data, graphNodeManager, random_key)
        self.route = data['data']['route']
        self.updateTime = float(data['data'].get('updateTime','0.2'))
        self.running = False
        self.last_contents = {}

    def execute(self, session_info: SessionInfo=None, exe_his: BaseExeHis=None, **kwargs):
        self.graphNodeManager.http_node.get_socketio_instance().start_background_task(self._send_all_process)
        self.graphNodeManager.project.register_project_process_route(self.route, self.name)

    def _send_all_process(self):
        while True:
            time.sleep(self.updateTime)
            # 创建字典项的副本进行迭代，避免原字典修改导致的错误
            for k, v in list(self.graphNodeManager.id_to_sessionInfo.items()):
                vhiss = v.get_newest_exe_his(5)
                d = {}
                has_changes = False
                session_id = v.id
                
                # 确保当前session在记录字典中存在
                if session_id not in self.last_contents:
                    self.last_contents[session_id] = {}
                
                for his in vhiss:
                    node_name = his.nodeName
                    current_content = his.get_content()
                    last_content = self.last_contents[session_id].get(node_name)
                    
                    # 检查内容是否有变化
                    if current_content != last_content:
                        d[node_name] = current_content
                        self.last_contents[session_id][node_name] = current_content
                        has_changes = True
                
                # 只有当有变化且d不为空时才发送
                if has_changes and d:
                    v.ws.emit(self.route, {'data': d}, room=v.id, namespace=v.full_url)